<script setup>
import { addUserService, changeUserStateService, deleteUserService, editUserService, getUserByIdService, getUserList } from '@/api/user'
import { ArrowRight, Delete, Edit, Search, Setting } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
// 获取用户列表的参数对象
const queryInfo = ref({
  query: '',
  // 当前的页数,
  pagenum: 1,
  // 每页显示多少条数据
  pagesize: 2,
})
// 用户列表数据
const userList = ref([])
// 总条数
const total = ref(0)
// 获取用户列表数据的方法
async function fetchUserList() {
  const { data: res } = await getUserList(queryInfo.value)
  if (res.meta.status !== 200) {
    // eslint-disable-next-line no-undef
    return ElMessage.error('获取用户列表失败')
  }
  userList.value = res.data.users
  total.value = res.data.total
  // console.log(res)
}
// 一进页面就发起请求获取用户列表数据
onMounted(() => {
  fetchUserList()
})
// 改变用户状态的方法
async function changeUserState(userInfo) {
  // console.log(userInfo)
  const { data: res } = await changeUserStateService(userInfo)
  if (res.meta.status !== 200) {
    userInfo.mg_state = !userInfo.mg_state
    // eslint-disable-next-line no-undef
    return ElMessage.error('修改用户状态失败')
  }
  // eslint-disable-next-line no-undef
  ElMessage.success('修改用户状态成功')
}
function handleSizeChange(newSize) {
  queryInfo.value.pagesize = newSize
  fetchUserList()
}
function handleCurrentChange(newPage) {
  queryInfo.value.pagenum = newPage
  fetchUserList()
}
// 控制添加用户对话框的显示和隐藏
const addDialogVisible = ref(false)
const addRuleFormRef = ref(null)
const addRuleForm = ref({
  username: '',
  password: '',
  email: '',
  mobile: '',
})
const addFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3|4578]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
}
function showAddDialog() {
  addDialogVisible.value = true
}
function addDialogClosed() {
  addRuleFormRef.value.resetFields()
}
function addForm() {
  addRuleFormRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }
    const { data: res } = await addUserService(addRuleForm.value)
    if (res.meta.status !== 201) {
      // eslint-disable-next-line no-undef
      return ElMessage.error('添加用户失败')
    }
    // eslint-disable-next-line no-undef
    ElMessage.success('添加用户成功')
    addDialogVisible.value = false
    fetchUserList()
  })
}
const editUserInfo = ref({
  id: '',
  username: '',
  email: '',
  mobile: '',
})
const editDialogVisible = ref(false)
const editRuleFormRef = ref(null)
const editFormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3|4578]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
}
// 根据id获取用户信息
async function getUserById(userInfo) {
  // console.log(userInfo)
  const { data: res } = await getUserByIdService(userInfo.id)
  // console.log(res)
  if (res.meta.status !== 200) {
    // eslint-disable-next-line no-undef
    return ElMessage.error('获取用户信息失败')
  }
  editUserInfo.value.id = res.data.id
  editUserInfo.value.username = res.data.username
  editUserInfo.value.email = res.data.email
  editUserInfo.value.mobile = res.data.mobile
}
function showEditDialog(row) {
  getUserById(row)
  editDialogVisible.value = true
}
function editForm() {
  editRuleFormRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }
    // console.log(editUserInfo.value)
    const { data: res } = await editUserService(editUserInfo.value)
    if (res.meta.status !== 200) {
      // eslint-disable-next-line no-undef
      return ElMessage.error('编辑用户信息失败')
    }
    // eslint-disable-next-line no-undef
    ElMessage.success('编辑用户信息成功')
    editDialogVisible.value = false
    fetchUserList()
  })
}
// 删除用户
async function deleteUser(row) {
  // console.log(row)
  // eslint-disable-next-line no-undef
  ElMessageBox.confirm(
    '此操作将永久删除该用户, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      const { data: res } = await deleteUserService(row.id)
      if (res.meta.status !== 200) {
        // eslint-disable-next-line no-undef
        return ElMessage.error('删除用户失败')
      }
      fetchUserList()
      // eslint-disable-next-line no-undef
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      // eslint-disable-next-line no-undef
      ElMessage({
        type: 'info',
        message: '已取消了删除',
      })
    })
}
</script>

<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/home' }">
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- a按钮区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            v-model="queryInfo.query"
            clearable
            placeholder="请输入内容"
            size="large"
            @clear="fetchUserList"
          >
            <template #append>
              <el-button :icon="Search" @click="fetchUserList" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button size="large" type="primary" :icon="Search" @click="showAddDialog">
            添加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" />
        <el-table-column prop="username" label="姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="mobile" label="电话" />
        <el-table-column prop="role_name" label="角色" />
        <el-table-column prop="mg_state" label="状态">
          <template #default="scope">
            <!-- {{ scope.row }} -->
            <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="操作">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" @click="showEditDialog(scope.row)" />
            <el-button type="danger" :icon="Delete" @click="deleteUser(scope.row)" />
            <el-tooltip
              :enterable="false"
              effect="dark"
              content="分配权限"
              placement="top"
            >
              <el-button type="warning" :icon="Setting" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        v-model:current-page="queryInfo.pagenum"
        v-model:page-size="queryInfo.pagesize"
        :page-sizes="[2, 3, 5, 10]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加用户"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        ref="addRuleFormRef"
        :rules="addFormRules"
        :model="addRuleForm"
        label-width="120px"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addRuleForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addRuleForm.password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addRuleForm.email" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addRuleForm.mobile" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addForm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑用户信息的对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户"
      width="50%"
      @close="editRuleFormRef.resetFields()"
    >
      <el-form
        ref="editRuleFormRef"
        :rules="editFormRules"
        :model="editUserInfo"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserInfo.username" disabled />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserInfo.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserInfo.mobile" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editForm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
